# coding=utf-8
from DBConnection import DBConnection


class DocSort(object):

    def __init__(self):
        """链接数据库"""
        self.connection = DBConnection('news', 'wangyi_news')
        self.connection.connection()

    def sort_by_relevancy(self, news_list):
        """
        按照相关度排序
        :param news_list: 查询所返回的文档id及其对应的相关度分数[[news_id, relevancy],[news_id, relevancy],...]
        :return: 按相关度排序后的文档ID
        """
        news_list.sort(key=lambda x: x[1], reverse=True)
        news = [x[0] for x in news_list]
        return news

    def sort_by_time(self, news_list):
        """
        按时间排序
        :param news_list: 查询所返回的文档id及其对应的相关度分数[[news_id, relevancy],[news_id, relevancy],...]
        :return: 按时间排序后的文档ID
        """
        news_id = [x[0] for x in news_list]
        news_time = self.connection.get_news_time(news_id)
        news = []
        for i in range(len(news_id)):
            news.append([news_id[i], news_time[i]])
        news.sort(key=lambda x: x[1], reverse=True)

        # print(news)
        news_by_time = [x[0] for x in news]
        return news_by_time

    def sort_by_heat(self, news_list):
        """
        按热度排序
        :param news_list: 查询所返回的文档id及其对应的相关度分数[[news_id, relevancy],[news_id, relevancy],...]
        :return:按热度排序后的文档ID
        """
        news_id = [x[0] for x in news_list]
        comment_num = self.connection.get_comment_num(news_id)
        news_time = self.connection.get_news_time(news_id)

        news = []
        for i in range(len(news_id)):
            news.append([news_id[i], comment_num[i], news_time[i]])

        # 首先按照时间排序，并给一个排名作为份数
        _by_time = sorted(news, key=lambda x: x[2], reverse=True)
        news_by_time = [x[0] for x in _by_time]
        for item in news:
            item.append((news_by_time.index(item[0])+1)*4)  # 时间占0.4的比重

        # 然后按照评论数进行排序并计算分数和
        _by_comment = sorted(news, key=lambda x: x[1], reverse=True)
        news_by_comment = [x[0] for x in _by_comment]
        for item in news:
            item[3] += ((news_by_comment.index(item[0])+1)*6)  # 评论数占0.6的比重
        _by_heat = sorted(news, key=lambda x: x[3])
        news_by_heat = [x[0] for x in _by_heat]
        return news_by_heat


if __name__ == '__main__':
    # 输入： news_list: 查询所返回的文档id及其对应的相关度分数[[news_id, relevancy],[news_id, relevancy],...]
    # 输出： 排序后的文档ID
    news_list = [['D55N97190001875N', 0.7], ['D54RIEMN00018AOQ', 0.6], ['D54RFIQV0001875N', 0.8], ['D4U09D14000187VE', 0.9], ['D4U0EB320001899N', 0.5], ['BNCIOHRU00014AED', 0.8]]
    doc_sort = DocSort()

    # 按相关度排序
    news = doc_sort.sort_by_relevancy(news_list)
    print(news)

    #按时间排序
    news = doc_sort.sort_by_time(news_list)
    print(news)

    # 按时间排序
    news = doc_sort.sort_by_heat(news_list)
    print(news)